package com.upyun.playdemo.fragment;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.upyun.playdemo.MainActivity;
import com.upyun.playdemo.R;
import com.upyun.playdemo.adapter.HistoryVideoAdapter;
import com.upyun.playdemo.mode.HistoryVideoInfo;
import com.upyun.playdemo.utils.Constant;
import com.upyun.playdemo.utils.OPENLOG;
import com.upyun.playdemo.view.PickerView;
import com.upyun.upplayer.widget.IRenderView;
import com.upyun.upplayer.widget.UpVideoView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * 历史视频回放界面.
 */
public class HistoryVideoPlaybackFragment extends BaseView {

    @InjectView(R.id.files_listview)
    ListView filesListview;
    @InjectView(R.id.year_pv)
    PickerView yearPv;
    @InjectView(R.id.month_pv)
    PickerView monthPv;
    @InjectView(R.id.day_pv)
    PickerView dayPv;
    @InjectView(R.id.search_btn)
    Button searchBtn;
    @InjectView(R.id.history_load_pb)
    ProgressBar historyLoadPb;
    @InjectView(R.id.history_kmplayer)
    UpVideoView historyKmplayer;

    private HistoryVideoAdapter mHistoryVideoAdapter;
    private List<String> mHistroyList;

    public HistoryVideoPlaybackFragment(Activity activity) {
        super(activity);
    }

    public static HistoryVideoPlaybackFragment newInstance(Activity activity) {
        HistoryVideoPlaybackFragment newFragment = new HistoryVideoPlaybackFragment(activity);
        return newFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_history_video_playback, null, false);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated() {
        OPENLOG.D("onActivityCreated===>2222");
        initAllDatas();
        initAllViews();
        updateNetWorkView();
         /* 测试韩工的播放器 */
        String path = "rtmp://live.hkstv.hk.lxdns.com/live/hks";
        path = "http://f117cdh.gnway.cc/planevod/record/zuoshang/2016-11-11/zuoshang-20161111-210310-210310-2.ts";
//        historyKmplayer.setVideoPath(path);
//        historyKmplayer.start();
    }

    private void initAllViews() {
        initVideoView();
        initPickerView();
        filesListview.setAdapter(mHistoryVideoAdapter);
        filesListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showMsg("请等待，正在加载中");
                historyLoadPb.setVisibility(View.VISIBLE); // 显示进度条.
                ((MainActivity) getActivity()).stopAllVideoAndAudio(1);
                String url = mHistroyList.get(position);
                historyKmplayer.setVideoPath(url);
                historyKmplayer.start();
            }
        });
    }

    private void initAllDatas() {
        mHistoryVideoAdapter = new HistoryVideoAdapter();
    }

    private void initPickerView() {
        Calendar c = Calendar.getInstance();
        final int year = c.get(Calendar.YEAR);
        final int month = c.get(Calendar.MONTH) + 1;
        final int day = c.get(Calendar.DAY_OF_MONTH);
        OPENLOG.D("%s年%s月%s日", year, month, day);
        List<String> yearList = new ArrayList<>();
        List<String> monthList = new ArrayList<>();
        List<String> dayList = new ArrayList<>();
        /* 年 */
        for (int i = 1988; i <= year; i++) {
            yearList.add("" + i);
        }
        /* 月份 */
        for (int i = 1; i <= 12; i++) {
            monthList.add("" + i);
            dayList.add("" + i);
        }
        /*  日 */
        for (int i = 13; i <= 31; i++) {
            dayList.add("" + i);
        }
        yearPv.setData(yearList);
        monthPv.setData(monthList);
        dayPv.setData(dayList);
        /* 设置当前年月份 */
        yearPv.setSelected(year + "");
        monthPv.setSelected(month + "");
        dayPv.setSelected(day + "");
    }

    private void initVideoView() {
        historyKmplayer.setAspectRatio(IRenderView.AR_16_9_FIT_PARENT);
        historyKmplayer.setMediaController(new MediaController(getActivity()));
        historyKmplayer.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(IMediaPlayer mp) {
                historyLoadPb.setVisibility(View.GONE); // 显示进度条.
            }
        });
    }

    @Override
    public void onRefresh() {
        updateNetWorkView();
    }

    @Override
    public void updateNetWorkView() {
        mUpdatehandler.sendEmptyMessageDelayed(-250, 2000);
    }

    @Override
    public void stopVideoView() {
        historyKmplayer.release(true);
        OPENLOG.D("stopVideoView==>>");
    }

    Handler mUpdatehandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                getHistoryVideoList();
            } catch (Exception e) {
                OPENLOG.E("" + e.getMessage());
                e.printStackTrace();
            }
        }
    };

    /**
     * 获取历史视频列表.
     */
    private void getHistoryVideoList() {
//        String time = "2016-11-11";
        String time = yearPv.getText() + "-" + monthPv.getText() + "-" + dayPv.getText();
        String url = String.format(Constant.ROOT_ADDR + Constant.RECORD_VIDEO_URL, Constant.VIDEO_ID, time);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        OPENLOG.D("url:" + url);
        asyncHttpClient.get(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    String data = new String(responseBody);
                    Gson gson = new Gson();
                    HistoryVideoInfo historyVideoInfo = gson.fromJson(data, HistoryVideoInfo.class);
                    Log.d("hailongqiu", "data:" + historyVideoInfo.toString());
                    if (historyVideoInfo != null) {
                        mHistroyList = historyVideoInfo.getResponse();
                        onRequsetSuccess(mHistroyList);
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                onRequestFailure();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                onRequestFailure();
            }
        });
    }

    private void onRequsetSuccess(List<String> histroyList) {
        mHistoryVideoAdapter.setHistoryItems(histroyList);
    }

    private void onRequestFailure() {
        Toast.makeText(getActivity(), "获取历史监控失败", Toast.LENGTH_SHORT).show();
    }

    @OnClick({R.id.search_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_btn: // 搜索关于日期内的历史录像视频.
                updateNetWorkView();
                break;
        }
    }

}
